package zry.User.Teacher;
import Connection.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class TeacherDAOImpl extends DAOBase implements TeacherDAO{
    private static final String TEACHER_SELECT_SQL = "SELECT * FROM teacher WHERE teacher_id=? and teacher_password=?";
    private static final String STUDENTS_SELECT_SQL = "SELECT student_id FROM student WHERE teacher=?";

    @Override
    public Teacher getTeacher(String teacher_id, String teacher_password) {
        Teacher teacher = null;
        Connection con = null;
        try {
            con = getConnection();
            PreparedStatement psmt = con.prepareStatement(TEACHER_SELECT_SQL);
            psmt.setString(1, teacher_id);
            psmt.setString(2, teacher_password);
            ResultSet rs = psmt.executeQuery();
            if (rs.next()) {
                teacher = new Teacher();
                teacher.setT_id(rs.getString("teacher_id"));
                teacher.setT_password(rs.getString("teacher_password"));
                teacher.setT_name(rs.getString("teacher_name"));
            }
            rs.close();
            psmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return teacher;
    }

    @Override
    public List<String> findStudents(String teacher_id)
    {
        List<String> StudentIds = new ArrayList<>();
        Connection con = null;
        try {
            con = getConnection();
            PreparedStatement psmt = con.prepareStatement(STUDENTS_SELECT_SQL);
            psmt.setString(1, teacher_id);

            ResultSet rs = psmt.executeQuery();
            while (rs.next()) {
                String s_id = rs.getString("student_id");
                StudentIds.add(s_id);
            }
            rs.close();
            psmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return StudentIds;
    }
}
